package com.example.demo.utils;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {
	private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

	/**
	 * 模拟请求
	 *
	 * @param url 资源地址
	 * @param map 参数列表
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public static String sendPostMap(String url, Map<String, String> map) {
		String body = null;
		try {
			// 创建httpclient对象
			CloseableHttpClient client = HttpClients.createDefault();
			// 创建post方式请求对象
			HttpPost httpPost = new HttpPost(url);
			// 装填参数
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			if (map != null) {
				for (Map.Entry<String, String> entry : map.entrySet()) {
					nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
				}
			}
			// 设置参数到请求对象中
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
			// 设置header信息
			// 指定报文头【Content-type】、【User-Agent】
			httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
			httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

			// 执行请求操作，并拿到结果（同步阻塞）
			CloseableHttpResponse response = client.execute(httpPost);
			// 获取结果实体
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				// 按指定编码转换结果实体为String类型
				body = EntityUtils.toString(entity, "UTF-8");
			}
			EntityUtils.consume(entity);
			// 释放链接
			response.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return body;
	}

	/**
	 * 模拟请求
	 *
	 * @param url       资源地址
	 * @param jsonArray 参数列表
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public static String sendPostArray(String url, JSONArray jsonArray) {
		String body = null;
		try {
			// 创建httpclient对象
			CloseableHttpClient client = HttpClients.createDefault();
			// 创建post方式请求对象
			HttpPost httpPost = new HttpPost(url);
			// 设置参数到请求对象中
			httpPost.setEntity(new StringEntity(jsonArray.toString(), "UTF-8"));
			// 设置header信息
			// 指定报文头【Content-type】、【User-Agent】
			httpPost.setHeader("Content-type", "application/json; charset=UTF-8");
			httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

			// 执行请求操作，并拿到结果（同步阻塞）
			CloseableHttpResponse response = client.execute(httpPost);
			// 获取结果实体
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				// 按指定编码转换结果实体为String类型
				body = EntityUtils.toString(entity, "UTF-8");
			}
			EntityUtils.consume(entity);
			// 释放链接
			response.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return body;
	}


	/**
	 * 模拟请求
	 *
	 * @param url 资源地址
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public static String sendGet(String url) throws IOException {
		String body = "";
		// 创建httpclient对象
		CloseableHttpClient client = HttpClients.createDefault();

		HttpGet httpGet = new HttpGet(url);
		// 设置header信息
		// 指定报文头【Content-type】、【User-Agent】
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000).setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
		httpGet.setConfig(requestConfig);
		httpGet.setHeader("Content-type", "application/json; charset=UTF-8");
		httpGet.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

		// 执行请求操作，并拿到结果（同步阻塞）
		CloseableHttpResponse response = client.execute(httpGet);

		// 获取结果实体
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			// 按指定编码转换结果实体为String类型
			body = EntityUtils.toString(entity, "UTF-8");
		}
		EntityUtils.consume(entity);
		// 释放链接
		response.close();
		return body;
	}


	/**
	 * get请求，带参数和请求头
	 *
	 * @param url 资源地址
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	public static String sendGetByHeaderAndParams(String url, Map<String, Object> headerMap, Map<String, Object> paramMap) throws IOException {
		String body = "";
		// 创建httpclient对象
		CloseableHttpClient client = HttpClients.createDefault();

		StringBuilder builder = new StringBuilder();
		builder.append(url);
		builder.append("?");

		String key;
		String value;
		if (paramMap != null && !paramMap.isEmpty()) {
			for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
				key = entry.getKey();
				value = entry.getValue() + "";
				builder.append("&" + key + "=" + value);
			}
		}

		HttpGet httpGet = new HttpGet(builder.toString());
		// 设置header信息
		// 指定报文头【Content-type】、【User-Agent】
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000).setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
		httpGet.setConfig(requestConfig);
		httpGet.setHeader("Content-type", "application/json; charset=UTF-8");
		httpGet.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

		if (headerMap != null && !headerMap.isEmpty()) {
			for (Map.Entry<String, Object> entry : headerMap.entrySet()) {
				httpGet.setHeader(entry.getKey(), entry.getValue() + "");
			}
		}

		// 执行请求操作，并拿到结果（同步阻塞）
		CloseableHttpResponse response = client.execute(httpGet);

		// 获取结果实体
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			// 按指定编码转换结果实体为String类型
			body = EntityUtils.toString(entity, "UTF-8");
		}
		EntityUtils.consume(entity);
		// 释放链接
		response.close();
		return body;
	}


	/**
	 * 发送POST请求
	 *
	 * @param url
	 * @param headerMap
	 * @param paramMap
	 * @return
	 */
	public static String sendPostByHeaderAndParams(String url, Map<String, Object> headerMap, Map<String, Object> paramMap) throws IOException {
		String body = null;
		// 创建httpclient对象
		CloseableHttpClient client = HttpClients.createDefault();
		// 创建post方式请求对象
		HttpPost httpPost = new HttpPost(url);
		// 装填参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		if (paramMap != null) {
			for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
				nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue() + ""));
			}
		}

		if (headerMap != null && !headerMap.isEmpty()) {
			for (Map.Entry<String, Object> entry : headerMap.entrySet()) {
				httpPost.setHeader(entry.getKey(), entry.getValue() + "");
			}
		}

		// 设置参数到请求对象中
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
		// 设置header信息
		// 指定报文头【Content-type】、【User-Agent】
		httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
		httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36");

		// 执行请求操作，并拿到结果（同步阻塞）
		CloseableHttpResponse response = client.execute(httpPost);
		// 获取结果实体
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			// 按指定编码转换结果实体为String类型
			body = EntityUtils.toString(entity, "utf-8");
		}
		EntityUtils.consume(entity);
		// 释放链接
		response.close();
		return body;

	}


	/**
	 * 发送get请求
	 *
	 * @param url 路径
	 * @return
	 */
	public static JSONObject httpGet(String url) {
		// get请求返回结果
		JSONObject jsonResult = null;
		CloseableHttpClient client = HttpClients.createDefault();
		// 发送get请求
		HttpGet request = new HttpGet(url);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(2000).setConnectionRequestTimeout(2000).setSocketTimeout(2000).build();
		request.setConfig(requestConfig);
		try {
			CloseableHttpResponse response = client.execute(request);

			// 请求发送成功，并得到响应
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				// 读取服务器返回过来的json字符串数组
				HttpEntity entity = response.getEntity();
				String strResult = EntityUtils.toString(entity, "utf-8");
				// 把json字符串转换成json对象
				jsonResult = JSONObject.parseObject(strResult);
			} else {
				logger.error("get请求提交失败:" + url);
			}
		} catch (IOException e) {
			logger.error("get请求提交失败:" + url, e);
		} finally {
			request.releaseConnection();
		}
		return jsonResult;
	}

}
